package interfaces.hud.pilot.equipment;

import org.fenggui.event.ButtonPressedEvent;
import org.fenggui.event.IButtonPressedListener;
import org.fenggui.util.Color;

import interfaces.GUISource;
import interfaces.PropertyContent;
import interfaces.hud.BasicHUD;
import interfaces.superWidgets.InterfaceButton;
import interfaces.superWidgets.StaticContent;
import logic.weapons.Weapon;
import logic.weapons.WeaponListener;
import logic.weapons.WeaponReloadEvent;

public class WeaponButton extends StaticContent {
	
	protected Weapon weapon;
	protected PropertyContent reloadContent;
	protected InterfaceButton weaponButton;
	
	public WeaponButton(Weapon weapon, int width, int height, BasicHUD hud) {
		super(width, height, 0, 0);
		this.weapon = weapon;
		
		int reloadHeight = height / 5;
		reloadContent = new PropertyContent(width, reloadHeight, 0, 0);
		addWidget(reloadContent);
		reloadContent.setMaxValue(100f);
		reloadContent.setValue(100f);
		
		hud.addListener(weapon, new WeaponListener() {
			@Override
			public void weaponReloading(WeaponReloadEvent event) {
				float percentage = event.getPercentage();
				changeReloadColor(percentage);
				reloadContent.setValue(percentage);
			}
		});
		
		weaponButton = new InterfaceButton(weapon.getWeaponName(), GUISource.middleFont);
		weaponButton.setSize(width, height - reloadHeight);
		weaponButton.setXY(0, reloadHeight);
		addWidget(weaponButton);
		addButtonListener();
		
		layout();
	}
	
	protected void addButtonListener() {
		weaponButton.addButtonPressedListener(new IButtonPressedListener() {
			@Override
			public void buttonPressed(ButtonPressedEvent e) {
				toggleWeaponStatus();
			}
		});
	}
	
	private void changeReloadColor(float percentage) {
		Color color = Color.BLUE.clone();
		if(percentage < 100f) {
			float r = percentage / 100f;
			float b = 1f - r;
			color.setColor(r, 0f, b, 1f);
		}
		
		reloadContent.changeValueColor(color);
	}
	
	private void toggleWeaponStatus() {
		weapon.setEnabled(!weapon.isEnabled());
		Color color = weapon.isEnabled() ? Color.WHITE : Color.BLUE;
		GUISource.setTextColor(weaponButton, color);
	}
	
	public Weapon getWeapon() { return weapon; }
}